package net.kong.sns.rest.client.friend;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;


import net.kong.sns.rest.client.InvalidResponseException;
import net.kong.sns.rest.client.KongApiMethod;
import net.kong.sns.rest.client.method.JsonMethodInvokeBase;
import net.kong.sns.rest.client.model.UserRelation;
import net.kong.sns.rest.client.rest.HttpResponseContent;


/**
 * @author yk
 * @version $Id: FriendsRelationMethodInvoke.java,v 1.3 2009/11/04 17:17:38 ningyubin Exp $
 */
public class FriendsRelationMethodInvoke extends JsonMethodInvokeBase<List<UserRelation>>{

    static Set<String> initializedFields = new HashSet<String>(){{add("user_ids1");add("user_ids2");add("type");}};
    
    public FriendsRelationMethodInvoke(String sessionKey,Collection<Long> userIds1,Collection<Long> userIds2){
        this(KongApiMethod.FRIENDS_ARE_FRIENDS, sessionKey, userIds1, userIds2);
    }
    
    protected FriendsRelationMethodInvoke(KongApiMethod method, String sessionKey,Collection<Long> userIds1,Collection<Long> userIds2) {
        super(method, sessionKey);
        if ( userIds1 == null || userIds2 == null || userIds1.isEmpty() || userIds2.isEmpty() ) {
            throw new IllegalArgumentException( "Collections passed to friends_areFriends should not be null or empty" );
        }
        if ( userIds1.size() != userIds2.size() ) {
            throw new IllegalArgumentException( 
                    String.format( "Collections should be same size: got userIds1: %d elts; userIds2: %d elts", userIds1.size(), userIds2
                    .size() ) );
        }
        ;
        setParameter("user_ids1", delimit(userIds1));
        setParameter("user_ids2", delimit(userIds2));
    }

    @Override
    protected List<UserRelation> processJsonResponse(HttpResponseContent responseData) throws InvalidResponseException {
        String response = responseData.getBody();
        Object o = reader.read(response);
        List<Map<String, Object>> relationList = (List<Map<String, Object>>) o;
        if (relationList.size() > 0) {
            List<UserRelation> ret=new ArrayList<UserRelation>();
            for(Map<String, Object> arelationjson:relationList){
                ret.add(trans(arelationjson));
            }
            return ret;
        }
        return null;
    }
    private UserRelation trans(Map<String, Object> arelationjson){
        UserRelation userRelation = new UserRelation();
        userRelation.initialize(arelationjson, initializedFields);
        return userRelation;
    }
}
